<script type="text/javascript">
//初始化行数
var trCount = ${salesOrderInstance?.salesOrderDetails?.size()?:0}
	trCount -=1
//添加行
function addOrderDetail(){
    //没有产品ID，返回
	if($("#searchProductId").val() == ''){
        alert('${message(code : 'b2b.salesOrder.page.selectProduct', default : 'Please select a product!')}');
		return false;
	}
    //锁定页面
    $.blockUI();
    //根据ID取产品信息
    $.ajax({
        url: "${createLink(controller:'salesOrderAjax', action: 'productProperty220')}",
        data: { serialNumber: $("#searchProductNumber").val() },
        dataType: "json",
        type: "POST",
        success: productPropertyCallback
    });
}
//根据返回的产品信息生成新的行
function productPropertyCallback(data){
    //解锁页面
    $.unblockUI();
    //行数加1
	trCount ++
    //行ID=行数+1
	var rowid = trCount + 1
    //达到最大行数
	if(rowid > 99){
		alert("max row is 100");
		return false;
	}
    //隔行变色
	var css = (trCount % 2 == 0)?"odd":"even";
    //价格
	var price = $("#searchProductPrice").html()
    //标准折扣
	var discount = data.discount
    //序号
	var serialNumber = (rowid < 10) ? '0' + rowid : '' + rowid
    //交付周期
	var deliveryCycle = data.delivery
    //增加行
	$("#salesOrderDetailList").append(
		$("<tr class='prop "+css+"' ></tr>").append(
			$("<td name='serialNumber'><span>"+serialNumber+"</span></td>").append(
				$('<input name="salesOrderDetails['+trCount+'].serialNumber" value="'+serialNumber+'" type="hidden" />')
			).append(
				$("<br/>")
			).append(
				$('<a href="#addSalesOrderDetailLink" delete="delete">${message(code: 'default.button.delete', default: 'Delete')}</a>').bind('click', myDeleteRow)
			)
		).append(
			$("<td name='product.id'></td>").append(
				$('<span>'+$("#searchProductNumber").val()+'</span>')
			).append(
				$('<input name="salesOrderDetails['+trCount+'].product.id" value="'+$("#searchProductId").val()+'" type="hidden" />')					
			)
		).append(
			$("<td name='product.name'></td>").append(
				$('<span>'+$("#searchProductName").html()+'</span>')
			)
		).append(
			$("<td name='product.standard'></td>").append(
				$('<span>'+$("#searchProductStandard").html()+'</span>')
			)
		).append(
			$("<td name='category'></td>").append(
				$('<span>'+(data.category?data.category:'')+'</span>')
			)
		).append(
			$("<td name='price' class='value number'></td>").append(
				$('<input name="salesOrderDetails['+trCount+'].price" value="'+$.formatNumber(price, "###,##0.000000")+'" readonly="readonly" />')
			).append(
                $('<span>('+data.allowZeroPrice+')</span>')
            )
		).append(
			$("<td name='discount' class='value number'></td>").append(
				$('<input name="salesOrderDetails['+trCount+'].discount" value="'+discount.toFixed(4) +'"  readonly="readonly" style="width:60px;" />')					
			)
		).append(
			$("<td name='quantity' class='value number'></td>").append(
				$("<input name='salesOrderDetails["+trCount+"].quantity' value='0' type='text' >").keypress(myKeypress).focus(myFocus).blur(myBlur).bind('paste', myPaste).change(myChange)
			)
		).append(
			$("<td name='deliveryLimitation'></td>").append(
				'<input type="hidden" name="salesOrderDetails['+trCount+'].deliveryLimitation" value="date.struct" />'
			).append(
				'<input type="hidden" name="salesOrderDetails['+trCount+'].deliveryLimitation_year" value=""/>'
			).append(
				'<input type="hidden" name="salesOrderDetails['+trCount+'].deliveryLimitation_month" value=""/>'
			).append(
				'<input type="hidden" name="salesOrderDetails['+trCount+'].deliveryLimitation_day" value=""/>'
			).append(
				$("<input target='salesOrderDetails["+trCount+"].deliveryLimitation' datepicker='datepicker' type='text' style='width:80px;'>").datepicker({
					  dateFormat: 'yy-mm-dd'
					, minDate: new Date(new Date().getTime() + deliveryCycle * 24 * 60 * 60 * 1000)
					, onClose: function(dateText, inst) {
						$('[name="'+$(this).attr('target') + '_year"]').val(inst.selectedYear)
						$('[name="'+$(this).attr('target') + '_month"]').val(inst.selectedMonth + 1)
						$('[name="'+$(this).attr('target') + '_day"]').val(inst.selectedDay)
					}
				}).attr("readonly", true)
			).append(
				$("<span>"+deliveryCycle+"</span>")
			)
		).append(
			$("<td name='amount' class='value number'>0.0000</td>")
		)
	)
    //重置搜索框
    initSearchProduct();
    //设置搜索框焦点
    $("#searchProductNumber").focus();
}
function myBlur(){
	var v = parseInt($.formatNumber(this.value, "##0.00"), 10);
        v = isNaN(v) ? $(this).data("before") : v;
	//set value
	this.value = $.formatNumber(v, "###,##0.00")
		
	//get value--parent quantity
	var parent_quantity = v
        parent_quantity = parseFloat(parent_quantity, 10)
	
    //get parent tr
	var parent_tr = $(this).parent().parent();
	
	//get parent price
	var parent_price = parent_tr.children("td[name=price]").children(":first-child").val()
        parent_price = $.formatNumber(parent_price, "#0.000000")
        parent_price = parseFloat(parent_price, 10)
	
	//get parent disocunt
	var parent_discount = parent_tr.children("td[name=discount]").children(":first-child").val()
        parent_discount = $.formatNumber(parent_discount, "#0.0000")
        parent_discount = parseFloat(parent_discount, 10)

	//parent amount
	var parent_amount_td = parent_tr.children("td[name=amount]")
	//get old row amount
	var old_row_amount = parent_amount_td.html()
		old_row_amount = $.formatNumber(old_row_amount, "##0.0000")
        old_row_amount = parseFloat(old_row_amount, 10)
	//calculate new row amount
	var new_row_amount = parent_price.mul(parent_discount).mul(parent_quantity)
	//set row amount
	parent_amount_td.html($.formatNumber(new_row_amount, "###,##0.0000"))

	//total amount
	var total_amount_td = $("td[name=totalAmount]")
    //get total amount
	var old_total_amount = total_amount_td.html()
		old_total_amount = $.formatNumber(old_total_amount, "##0.0000")
        old_total_amount = parseFloat(old_total_amount, 10)
    //calculate new total amount
	var new_total_amount = old_total_amount.sub(old_row_amount).add(new_row_amount)

    //set total amount
	total_amount_td.html($.formatNumber(new_total_amount, "###,##0.0000"))
}

function myDeleteRow(){
    if($(this).parent().parent().parent().attr("id") != 'salesOrderDetailList'){
        return false;
    }
	if(!confirm('Delete!')){
		return false;
	}
	//get parent tr
	var parent_tr = $(this).parent().parent();
	
	//get row amount
	var amount = $(parent_tr).children("td[name=amount]").html().trim()
		amount = $.formatNumber(amount, "#0.0000")
        amount = parseFloat(amount, 10)
	var total_amount_td = $("td[name=totalAmount]")		
	//get total amount
	var old_total_amount = total_amount_td.html()
		old_total_amount = $.formatNumber(old_total_amount, "##0.00")
        old_total_amount = parseFloat(old_total_amount, 10)
	//calculate new total amount
	var new_total_amount = old_total_amount.sub(amount)

	//set total amount
	total_amount_td.html($.formatNumber(new_total_amount, "###,##0.0000"))
	
	$(parent_tr).remove()

	refreshSerialNumber();
}

function refreshSerialNumber(){
	var rowindex = -1
	//get table all row
	$("#salesOrderDetailList > tr").each(function(){
		rowindex ++;
		var new_serialNumber = (rowindex + 1 < 10)? "0" + (rowindex + 1) : "" + (rowindex + 1);
	    $(this).children("td").each(function(){
			switch($(this).attr('name')){
				case 'serialNumber':
					$(this).children(":nth-child(1)").html(new_serialNumber);
					$(this).children(":nth-child(2)").val(new_serialNumber);
				case 'product.id':
				case 'price':
				case 'discount':
				case 'contractDetail.id':
				case 'specialDiscount':
				case 'finalDiscount':
				case 'quantity':
				case 'deliveryLimitation':
				case '':
					$(this).children("input").each(function(){
						var old_name=$(this).attr("name")||$(this).attr("target");
						var begin = old_name.indexOf("[", 0);
						var end = old_name.indexOf("]", begin);
						var new_name = old_name.substring(0, begin + 1) + rowindex + old_name.substr(end);
						//$(this).attr("name", new_name).attr("id", new_name);
						if($(this).attr("name")){$(this).attr("name", new_name)}
						if($(this).attr("id")){$(this).attr("id", new_name)}
						if($(this).attr("target")){
							var deliveryCycle = $(this).parent().children(":last-child").html().replace(/\r\n/g, "").trim();
							
							$(this).attr("target", new_name).datepicker("destroy").datepicker({
								dateFormat: 'yy-mm-dd'
								, minDate: new Date(new Date().getTime() + deliveryCycle * 24 * 60 * 60 * 1000)
								, onClose: function(dateText, inst) {
									$('[name="'+$(this).attr('target') + '_year"]').val(inst.selectedYear)
									$('[name="'+$(this).attr('target') + '_month"]').val(inst.selectedMonth + 1)
									$('[name="'+$(this).attr('target') + '_day"]').val(inst.selectedDay)
								}
							})
						}
					})
					break;
			}

		})
	})
    trCount = rowindex;
}

</script>
